﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using BitwiseOre.SharedMemory.JetBrains;

namespace BitwiseOre.SharedMemory.Core.Primatives
{
    [UsedImplicitly]
    internal sealed class IndexQueueLayout : IIndexQueueLayout
    {
        private const int HeadIndex = 0;
        private const int TailIndex = 1;
        private const int DummyIndex = 2;

        private readonly IIntArray _array;

        public IndexQueueLayout(IIntArray array)
        {
            _array = array;
        }

        public CountedIndex Head
        {
            get { return (CountedIndex) _array[HeadIndex]; }
            set { _array[HeadIndex] = value; }
        }

        public CountedIndex Tail
        {
            get { return (CountedIndex) _array[TailIndex]; }
            set { _array[TailIndex] = value;}
        }

        public int Dummy
        {
            get { return _array[DummyIndex]; }
            set { _array[DummyIndex] = value; }
        }

        public bool CasHead(CountedIndex comparand, CountedIndex value)
        {
            return _array.InterlockedCompareExchange(HeadIndex, comparand, value);
        }

        public bool CasTail(CountedIndex comparand, CountedIndex value)
        {
            return _array.InterlockedCompareExchange(TailIndex, comparand, value);
        }

        public bool CasDummy(int comarand, int value)
        {
            return _array.InterlockedCompareExchange(DummyIndex, comarand, value);
        }
    }
}